package aliyun

import (
	"fmt"
	"gitee.com/wuennan/cloudstation/store"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"github.com/go-playground/validator/v10"
)
var validate = validator.New()
func NewUploader(endpoint, ak, sk string) (store.Uploader,error) {
	uploader:=&aliyun{
		Endpoint: endpoint,
		Ak:       ak,
		Sk:       sk,
		lintener: NewListener(),
	}
	if err := uploader.validate(); err != nil{
		return nil,err
	}
	return uploader,nil
}

type aliyun struct {
	// 结构体的值时必须（要有）的
	Endpoint string	`validate:"required,url"`
	Ak       string `validate:"required"`
	Sk       string `validate:"required"`
	lintener oss.ProgressListener
}

func (a *aliyun) validate() error {
	return validate.Struct(a)
}

func (a *aliyun) UploadFile(bucketName, objectKey, filePath string) error {
	client, err := oss.New(a.Endpoint, a.Ak, a.Sk)
	if err != nil {
		return err
	}

	bucket, err := client.Bucket(bucketName)
	if err != nil {
		return err
	}

	err = bucket.PutObjectFromFile(objectKey, filePath,oss.Progress(a.lintener))
	if err != nil {
		return err
	}

	signedURL, err := bucket.SignURL(objectKey, oss.HTTPGet, 60*60*24)
	if err != nil {
		return fmt.Errorf("SignURL error, %s", err)
	}
	fmt.Printf("下载链接: %s\n", signedURL)
	fmt.Println("\n注意: 文件下载有效期为1天, 中转站保存时间为3天, 请及时下载")

	return nil
}
